#!/usr/bin/env python

import sys
import shutil
import os
import xml.dom.minidom

def fixLogPaths(newVirtualDirectory, prefix):
    # Update the log paths
    log4netFile = os.path.join(newVirtualDirectory, 'log4net.config')
    doc = xml.dom.minidom.parse(log4netFile)

    for param in doc.getElementsByTagName('param'):
        if param.getAttribute('name') == 'File' and \
           param.hasAttribute('value'):
            fileValue = param.getAttribute('value')
            (d, f) = os.path.split(fileValue)
            f = prefix + '.' + f
            # don't use os.path.join because log4net really likes forward slashes
            param.setAttribute('value', d + '/' + f)
    file(log4netFile, 'wb').write(doc.toxml())
    
def main(args=None):
    if args == None:
        args = sys.argv[1:]

    if len(args) == 0:
        print sys.argv[0], '<originalDir> <prefix>'
        return 0
    
    originalDir = args[0]
    prefix = args[1]

    # Copy the directory
    newDir = prefix + '.' + originalDir
    shutil.copytree(originalDir, newDir)

    fixLogPaths(newDir, prefix)

    return 0


if __name__ == '__main__':
    sys.exit(main())

